package com.kevin.io.jdk.nio;

import java.nio.ByteBuffer;

/**
 * @author Kevin Liu
 * @date 2020/8/27 11:17 上午
 */
public class BufferTest {

    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        System.out.printf("capacity容量：%s, position位置：%s, limit限制：%s%n", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit());
        byteBuffer.put((byte) 1);
        byteBuffer.put((byte) 2);
        byteBuffer.put((byte) 3);
        System.out.printf("写入3字节后，capacity容量：%s, position位置：%s, limit限制：%s%n", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit());

        //切换为读模式
        byteBuffer.flip();
        System.out.printf("写入3字节后，capacity容量：%s, position位置：%s, limit限制：%s%n", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit());
        System.out.println(byteBuffer.get());
        System.out.println(byteBuffer.get());
        System.out.printf("读了两字节后 capacity容量：%s, position位置：%s, limit限制：%s%n", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit());

        //把已经读了的删除掉 并切换到写模式
        byteBuffer.compact();
        System.out.printf("清除已读后 capacity容量：%s, position位置：%s, limit限制：%s%n", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit());
        byteBuffer.put((byte) 4);
        byteBuffer.put((byte) 5);
        byteBuffer.put((byte) 6);
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()) {
            System.out.println(byteBuffer.get());
        }
        System.out.printf("读完后 capacity容量：%s, position位置：%s, limit限制：%s%n", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit());

        byteBuffer.clear();
        System.out.printf("clear后 capacity容量：%s, position位置：%s, limit限制：%s%n", byteBuffer.capacity(),
                byteBuffer.position(), byteBuffer.limit());
    }
}
